const fs = require('fs');
const path = require('path');
const iconv = require('iconv-lite');
const readline = require('readline');

var filename = path.join(__dirname, './wmbyy.lrc');
var streamReader = fs.createReadStream(filename)
var rl = readline.createInterface({ input: streamReader });

var lines
fs.readFile(path.join(__dirname, './wmbyy.lrc'), (error, data) => {
    lines = iconv.decode(data, 'UTF-8').split('\n');
    console.log(lines, lines.length)
})

function sends() {
    var regex = /\[(\d{2})\:(\d{2})\.(\d{2})\](.+)/;
    var begin = new Date().getTime();
// rl.on('line', (line) => {
//     console.log(line)
//     task(line, begin);
// });
    lines.forEach((line) => {
        task(line, begin);
    })


    function task(line, begin) {
        console.log(typeof line)
        var matches = regex.exec(line);
        // console.log(matches)
        if (matches) {
            var m = parseFloat(matches[1]);
            var s = parseFloat(matches[2]);
            var f = parseFloat(matches[3]);
            var lyric = matches[4]; // 当前行歌词不是立即执行
            // 由于下达输出任务的时刻不同
            var offset = new Date().getTime() - begin;
            setTimeout(() => {
                console.log(lyric);
                wss.clients.forEach(function each(client) {
                    client.send(lyric);
                });
            }, m * 60 * 1000 + s * 1000 + f - offset);
        } else {
            // 不是一行歌词
            console.log(line);
            wss.clients.forEach(function each(client) {
                client.send(line);
            });
        }
    }
}
 



const WebSocket = require('ws');

const WebSocketServer = WebSocket.Server;

const wss = new WebSocketServer({
    port: 3000
});

let count = 0;

wss.on('connection', function (ws) {
    console.log(`[SERVER] connection()`);
    sends()
    ws.on('message', function (message) {
        console.log(`[SERVER] Received: ${message}`);
        setTimeout(() => {
            // ws.send(`What's your name? ${count++}`, (err) => {
            //     if (err) {
            //         console.log(`[SERVER] error: ${err}`);
            //     }
            // });
            wss.clients.forEach(function each(client) {
                client.send(`I'm server: ${count++}`);
            });
        }, 100);
    })
});

console.log('ws server started at port 3000...');

// client test:

// let count = 0;

// let ws = new WebSocket('ws://localhost:3000/ws/chat');

// ws.on('open', function () {
//     console.log(`[CLIENT] open()`);
//     ws.send('Hello!');
// });

// ws.on('message', function (message) {
//     console.log(`[CLIENT] Received: ${message}`);
//     count++;
//     if (count > 3) {
//         ws.send('Goodbye!');
//         ws.close();
//     } else {
//         setTimeout(() => {
//             ws.send(`Hello, I'm Mr No.${count}!`);
//         }, 1000);
//     }
// });
